const fs = require('fs')
const studyName = '基本面50指数PE双均线估值定投'
const idList = ['SSE:600036', 'SSE:601318', 'SSE:601166', 'SSE:601668', 'SSE:601398', 'SSE:601328', 'SZSE:000002', 'SSE:600028', 'SSE:600104', 'SZSE:000333']
const weightList = [7.76, 7.76, 6.99, 4.25, 3.97, 3.63, 3.08, 2.99, 2.98, 2.75]
const contextList = []

const main = () => {
    contextList.push(`// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sword_snow

//@version=4
study('${studyName}')

sumWeight = 0.0
stockCount = 0
weightList = array.new_float(0)
peList = array.new_float(0)
averagePE = 0.0
_EPS = 0.0
_close = 0.0
_PE = 0.0
_weight = 0.0
    `)

    if (idList.length !== weightList.length) {
        throw new Error('id 数量必须和权重数量相同')
    }

    for (let i = 0; i < idList.length; i++) {
        contextList.push(`
// ↓ 复制单元 ------
stockCount += 1
_weight := ${weightList[i]}
_EPS := financial('${idList[i]}', "EARNINGS_PER_SHARE", "TTM")
_close := security('${idList[i]}', "W", close)
_PE := _close / _EPS
array.push(peList, _PE)
array.push(weightList, _weight)
// ↑ --------------
        `)
    }

    contextList.push(`
sumWeight := array.sum(weightList)

for _i = 0 to stockCount - 1
    averagePE += array.get(peList, _i) * (array.get(weightList, _i) / sumWeight)

pe25Ma = sma(averagePE, 25)
pe5Ma = sma(averagePE, 5)

plot(averagePE, color=#db5a6b, linewidth=2)
plot(pe25Ma, color=#00bc12)
plot(pe5Ma, color=color.yellow)
    `)

    fs.writeFileSync(`./${studyName}.pine`, contextList.join('\n'), 'utf8')

}


main()
